<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button type="text" size="small" icon="el-icon-view" @click="detailEvent(row)">详 情</el-button>
      </template>
      <template slot-scope="{ row }" slot="sourceType">
        <span>{{ row.sourceType == 'ERP' ? 'ERP同步' : 'MES新增' }}</span>
      </template>
    </avue-crud>
    <el-dialog class="showDialog" append-to-body :close-on-click-modal="false" title="详情" :visible.sync="showDialog" v-if="showDialog" width="60%" top="7vh">
      <div class="titleIcon">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <h4>供应商退料单信息</h4>
      </div>
      <avue-form ref="properties" v-model="properties" :option="propertiesOption"></avue-form>
      <div class="titleIcon">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <h4>物料详情</h4>
      </div>
      <avue-crud
        :option="sheetOption"
        :table-loading="detailLoading"
        :data="sheetData"
        :page.sync="detailPage"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="sheetForm"
        ref="addTableCrud"
        @selection-change="selectionDetailChange"
        @current-change="currentDetailChange"
        @size-change="sizeDetailChange"
      >
      </avue-crud>
      <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    </el-dialog>

    <el-dialog append-to-body :close-on-click-modal="false" :title="title" :visible.sync="showDetailDialog" width="60%" top="7vh" class="detail-dialog">
      <h3>请填写退货数量</h3>
      <avue-crud :option="detailOption" ref="detailTableCrud" @selection-change="selectionPoDetailChange" :key="timer" :table-loading="poDetailLoading" :data="sheetDetails">
      </avue-crud>
      <div class="dialog-footer" v-if="title !== '详情'">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-circle-plus-outline"
          :disabled="this.selectionPoDetailList.length == 0 && title !== '编辑'"
          @click="handleSubmit()"
          v-preventReClick
          >保存</el-button
        >
        <el-button size="small" icon="el-icon-circle-close" @click="showDetailDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, getDetailList, remove } from '@/api/warehouse/purchase-return';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'PUERCHASE_RETURN',
      form: {},
      typeObj: {},
      sheetType: '', //采购单类型
      sheetForm: {},
      properties: {},
      showDetailDialog: false,
      timer: new Date().getTime(),
      loading: false,
      detailLoading: false,
      poDetailLoading: false,
      isNone: '', //是否显示修改
      status: '',
      tableOption: [], //模态框配置
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      rowData: {}, //行数据
      selectionList: [],
      selectionDetailList: [],
      selectionPoDetailList: [],
      showDialog: false,
      data: [],
      sheetData: [],
      sheetDetails: [],
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuPosition: 'right',
        searchMenuSpan: 4,
        dialogClickModal: false,
        border: true,
        height: 'calc(100vh - 406px)',
        viewBtn: false,
        addBtn: false,
        selection: false,
        printBtn: false,
        editBtn: false,
        delBtn: false,
        index: true,
        indexLabel: '序号',
        searchSpan: 5,
        columnBtn: false,
        menu: true,
        column: [
          {
            label: '退货单号',
            prop: 'returnOrderNo',
            search: true,
            searchSpan: 6,
            searchOrder: 1,
            rules: [
              {
                required: true,
                message: '请输入退货单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '供应商',
            prop: 'vendorName',
            search: true,
            searchSpan: 6,
            searchOrder: 3,
            overHidden: true,
            rules: [
              {
                required: true,
                message: '请输入供应商',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '单据状态',
            prop: 'status',
            search: true,
            searchSpan: 6,
            searchOrder: 6,
            type: 'select',
            dataType: 'string',
            dicData: [
              { label: '正常', value: '1' },
              { label: '完成', value: '2' },
              { label: '取消', value: '3' },
              { label: '关闭', value: '4' }
            ]
          },
          {
            label: '来源',
            prop: 'sourceType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=sheet_source',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          }
        ]
      },
      propertiesOption: {
        labelWidth: '130',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '供应商退料单号',
            prop: 'returnOrderNo',
            disabled: true,
            span: 7
          },
          {
            label: '供应商',
            prop: 'vendorName',
            disabled: true,
            span: 7
          },
          {
            label: '单据状态',
            prop: 'status',
            type: 'select',
            dataType: 'string',
            dicData: [
              { label: '正常', value: '1' },
              { label: '完成', value: '2' },
              { label: '取消', value: '3' },
              { label: '关闭', value: '4' }
            ],
            disabled: true,
            span: 7
          }
        ]
      },
      detailOption: {
        height: '400',
        addBtn: false,
        viewBtn: false,
        selection: false,
        menu: false,
        page: false,
        index: false,
        border: true,
        selection: true,
        refreshBtn: false,
        column: [
          {
            label: '单行号',
            prop: 'purchaseOrderLot'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '采购数量',
            prop: 'quantity'
          },
          {
            label: '已入库数量',
            prop: 'storageQuantity'
          },
          {
            label: '已收数量',
            prop: 'receivingQuantity'
          },
          {
            label: '退货数量',
            prop: 'returnQuantity',
            type: 'number',
            precision: 10,
            controls: false,
            cell: true
          },
          {
            label: '退货原因',
            prop: 'returnReason',
            cell: true
          },
          {
            label: '单位',
            prop: 'uom'
          }
        ]
      },
      sheetOption: {
        tip: false,
        searchShow: true,
        searchSpan: 4,
        searchMenuSpan: 6,
        dialogClickModal: false,
        height: '400',
        border: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        cancelBtn: false,
        saveBtn: false,
        selection: true,
        menu: false,
        page: false,
        index: false,
        indexLabel: '序号',
        refreshBtn: false,
        expandBtn: false,
        column: [
          {
            label: '行号',
            prop: 'sourceSheetLot'
          },
          {
            label: '采购单号',
            prop: 'sourceSheetNo'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料规格',
            prop: 'partSpec'
          },
          {
            label: '物料品牌',
            prop: 'partBrand'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '计划退料数量',
            prop: 'planReturnQuantity'
          },
          {
            label: '实际退料数量',
            prop: 'actualReturnQuantity'
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.purchaseReturn_add, false),
        viewBtn: this.vaildData(this.permission.purchaseReturn_view, false),
        delBtn: this.vaildData(this.permission.purchaseReturn_delete, false),
        editBtn: this.vaildData(this.permission.purchaseReturn_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    detailEvent(row) {
      this.showDialog = true;
      this.properties = row;
      this.onDetailLoad(this.detailPage, { returnOrderNo: row.returnOrderNo });
    },
    onDetailLoad(page, params) {
      this.detailLoading = true;
      getDetailList(page.currentPage, page.pageSize, params)
        .then((res) => {
          const data = res.data.data;
          this.detailPage.total = data.total;
          this.sheetData = data.records;
        })
        .finally(() => {
          this.detailLoading = false;
        });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    selectionPoDetailChange(list) {
      this.selectionPoDetailList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentDetailChange(currentPage) {
      this.detailPage.currentPage = currentPage;
      this.onDetailLoad(this.detailPage);
    },
    sizeDetailChange(pageSize) {
      this.detailPage.pageSize = pageSize;
      this.onDetailLoad(this.detailPage);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    reset() {},
    /**
     * 新增模态框
     */
    handleAddBtn() {
      this.title = '新增';
      this.showDialog = true;
      this.resetData();
    },

    /**
     * 选择模态框数据
     */
    async getSelectedRows(rowData, titleInfo) {
      switch (titleInfo) {
        // 采购单
        case 'purchaseOrderNo':
          this.properties.purchaseOrderNo = rowData.purchaseOrderNo;
          this.sheetData = structuredClone([rowData]);
          break;
        default:
          break;
      }
    },
    /*
     *下一步
     */
    handleNextStep() {
      this.addDisFn();
      this.$refs.properties.validate((valid, done) => {
        if (valid) {
          if (this.selectionDetailList.length <= 0) {
            this.$message.warning('请先选择需退货的物料!');
            return;
          }
          this.sheetDetails = this.addTableData(this.selectionDetailList);
          this.showDetailDialog = true;
        }
      });
    },
    /*
     * 提交
     */
    handleSubmit() {
      const that = this;
      this.$refs.detailTableCrud.validateCellForm().then((res) => {
        let obj = res || {};
        if (Object.keys(obj).length === 0) {
          let data = that.selectionPoDetailList[0];
          delete data.id;
          let params = {
            ...data,
            actualReturnQuantity: data.returnQuantity
          };
          add(params).then(() => {
            this.$message.success(`${this.title === '新增' ? '新增' : '编辑'}成功!`);
            this.showDetailDialog = false;
            this.showDialog = false;
            this.resetData();
            this.refreshChange();
          });
        }
      });
    },

    /**
     * 添加单据物料数据 PO
     */
    addTableData(data) {
      let tempArr = [];
      for (let i = 0; i < data.length; i++) {
        let item = {
          ...data[i],
          $cellEdit: true
        };
        this.title === '详情' && delete item.$cellEdit;
        tempArr.push(item);
      }
      return this._orderBy(tempArr, ['purchaseOrderLot'], ['asc']);
    },

    //数据重置
    resetData() {
      this.sheetData = [];
      this.sheetDetails = [];
      this.properties = {};
    },

    /**
     * 采购单号模态框
     */
    openPurchaseOrderModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择采购单信息（双击进行选择）',
        url: '/api/mes-warehouse/purchase-order/page',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        titleInfo: 'purchaseOrderNo',
        columnDefs: [
          {
            label: '采购单号',
            prop: 'purchaseOrderNo',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入采购单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '行号',
            prop: 'purchaseOrderLot'
          },
          {
            label: '供应商名称',
            prop: 'vendorName'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '单据状态',
            prop: 'status',
            search: true,
            type: 'select',
            dataType: 'string',
            dicData: [
              { label: '正常', value: '1' },
              { label: '完成', value: '2' },
              { label: '取消', value: '3' },
              { label: '关闭', value: '4' }
            ]
          }
        ]
      };
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    column(prop) {
      return this.findObject(this.sheetOption.column, prop);
    },
    formColumn(prop) {
      return this.findObject(this.propertiesOption.column, prop);
    },
    /**
     * 查看禁用
     */
    viewDisFn() {
      this.detailOption.selection = false;
    },
    /**
     * 编辑禁用
     */
    editDisFn() {
      this.detailOption.selection = false;
    },
    /**
     * 添加禁用
     */
    addDisFn() {
      this.detailOption.selection = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  padding-top: 20px;
  justify-content: flex-end;
}

::v-deep .el-dialog .avue-crud__menu {
  display: none;
}
.titleIcon {
  display: flex;
  align-items: center;
}
</style>
